//
//  ViewController.swift
//  AutoModel
//
//  Created by 好米有易 on 2019/8/1.
//  Copyright © 2019 own. All rights reserved.
//

import Cocoa
import SnapKit
import Highlightr

class ViewController: NSViewController {

    var finalString = ""

   private lazy var modelView: GGTextView = {
        let modelView = GGTextView()
        return modelView;
    }()

   private lazy var jsonView: GGTextView = {
        let jsonView = GGTextView()
        return jsonView;
    }()

   private lazy var tableView: NSCollectionView = {
        let tableView = NSCollectionView()
        let flowLayout = NSCollectionViewFlowLayout()
        flowLayout.itemSize = NSSize(width: MIN_WIDTH / 2 - 50, height: 50)
        flowLayout.sectionInset = NSEdgeInsets(top: 10.0, left: 10, bottom: 10.0, right: 10)
        flowLayout.minimumInteritemSpacing = 0.0
        flowLayout.minimumLineSpacing = 10.0
        tableView.collectionViewLayout = flowLayout
        tableView.isSelectable = true
        tableView.register(Item.self, forItemWithIdentifier: NSUserInterfaceItemIdentifier("item"))
        tableView.dataSource = self
        return tableView
    }()

   private lazy var indicator: NSProgressIndicator = {
        let indicator = NSProgressIndicator()
        indicator.style = .spinning
        indicator.wantsLayer = true
//        indicator.layer?.backgroundColor = NSColor.lightGray.cgColor
        indicator.isHidden = true
    indicator.frame.size = NSSize(width: 60, height: 60)
        indicator.controlSize = NSControl.ControlSize.regular
        indicator.sizeToFit()
        return indicator
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
    }

    @IBAction func makeStructs(_ sender: Any) {
        print("makeStructs")
        let panel = NSSavePanel.init()
        panel.title = "保存文件"
        panel.message = "请选择文件路径"
        panel.nameFieldStringValue = "FileName"
        panel.allowsOtherFileTypes = true
        panel.allowedFileTypes = ["swift", "h", "m"]
        panel.isExtensionHidden = false
        panel.canCreateDirectories = true
        panel.beginSheetModal(for: NSApplication.shared.windows.first!) { (response) in
            if response == NSApplication.ModalResponse.OK {
                guard let path = panel.url?.path else {return}
                guard let data = self.finalString.data(using: String.Encoding.utf8) else {return}
                let manager = FileManager.default
                let createSuccess = manager.createFile(atPath: path,contents:data,attributes:nil)
                print("文件创建结果: \(createSuccess)")
            }
        }
    }


    override var representedObject: Any? {
        didSet {
            print("representedObject")
        }
    }
}

// MARK: - action
extension ViewController {

    //根据文件名和路径创建文件
    func createFile(name:String, fileBaseUrl:URL, string: String){
        let manager = FileManager.default

        let file = fileBaseUrl.appendingPathComponent(name)
        print("文件: \(file)")
        let exist = manager.fileExists(atPath: file.path)
        if !exist {
            //在文件中随便写入一些内容
            let data = string.data(using: String.Encoding.utf8)
            let createSuccess = manager.createFile(atPath: file.path,contents:data,attributes:nil)
            print("文件创建结果: \(createSuccess)")
        }
    }

}

// MARK: - UI
extension ViewController {
    func setupUI() -> () {
        view.set(color: .brown)

        view.addSubview(modelView)
        modelView.snp.makeConstraints { (make) in
            make.edges.equalTo(NSEdgeInsets(top: 0, left: CGFloat(MIN_WIDTH / 2), bottom: 0, right: 0))
        }

        view.addSubview(jsonView)
        jsonView.snp.makeConstraints { (make) in
            make.edges.equalTo(NSEdgeInsets(top: 0, left: 0, bottom: 0, right: CGFloat(MIN_WIDTH / 2)))
        }

         view.addSubview(indicator)
        indicator.snp.makeConstraints { (make) in
            make.center.equalTo(view.snp_center)
            make.size.equalTo(60)
        }

    }
}

// MARK: - NET
extension ViewController {
    func request(type: RequstType, url: String, paraters: [String : Any]?) {
        self.indicator.startAnimation()

        /// 字符串后不能直接拼接参数 例如"https://www.apiopen.top/weatherApi?city=成都" 不能转换为URL
//        https://api.apiopen.top/getJoke?page=1&count=2&type=video
//        let str = "https://www.apiopen.top/weatherApi"
//        https://api.apiopen.top/videoCategory
//                let str = "https://api.apiopen.top/videoCategory"

        NetworkManager.shared.request(type: type, url: url, paraters: paraters) { (data:Data) in

            guard let result = try? (JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.init()) as! [String : Any]) else {return}

            DispatchQueue.main.async(execute: {

                if let jsonString = String(data: data, encoding: String.Encoding.utf8) {
                    let highlight = Highlightr()
                    highlight?.setTheme(to: "paraiso-dark")
                    guard let highlightedCode = highlight?.highlight(jsonString.jsonFormatPrint(), as: "json") else {return}
                    self.jsonView.setCodeText(string: highlightedCode)
                    if let thomeColor = highlight?.theme.themeBackgroundColor {
                        self.jsonView.setTheme(color: thomeColor)
                    }
                }

                let highlight = Highlightr()
                highlight?.setTheme(to: "xcode")
                guard let highlightedCode = highlight?.highlight(ModelManager.shared.makeModel(name: "FileName", data: result), as: "swift") else {return}
                self.modelView.setCodeText(string: highlightedCode)

                if let thomeColor = highlight?.theme.themeBackgroundColor {
                    self.modelView.setTheme(color: thomeColor)
                }

                self.indicator.stopAnimation()

            })

        }
    }
}

// MARK: - Delegate
extension ViewController: NSCollectionViewDelegate {
    func collectionView(_ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set<IndexPath>) {
        print(indexPaths)
    }
}


// MARK: - DataSource
extension ViewController: NSCollectionViewDataSource {


    func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
        return 20
    }

    func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {

        let item =  collectionView.makeItem(withIdentifier: NSUserInterfaceItemIdentifier("item"), for: indexPath) as! Item

        return item
    }
}
